package com.september.afterclient;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.ws.rs.core.MediaType;

import com.google.gson.Gson;
import com.september.mongo.entities.User;
import com.september.prop.Properteer;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

public class AuthClient {

	private String path;
	private Properties prop;
	private Client client;
	private AfterClient afterClient;
	
	public AuthClient() {
		prop = Properteer.getInstance().Properties() ;
		path = prop.getProperty("HOST")+prop.getProperty("AUTH_PATH");
		client = Client.create();
		afterClient = new AfterClient();
		
	}
	
	public User logIn(String user, String pwd) {
		String requestPath = prop.getProperty("SIGNUP");
		WebResource webResource = client
				   .resource(path+requestPath);
		Map<String,String> logParams = new HashMap<String, String>();
		logParams.put("USER", user);
		logParams.put("PASSWORD",pwd);
		Gson gson = new Gson();
		ClientResponse response = webResource.type(MediaType.APPLICATION_JSON).post(ClientResponse.class,  gson.toJson(logParams));
		
		if (response.getStatus() != 201) {
			Properteer.getInstance().getLogger(this.getClass()).debug("Failed : HTTP error code : " + response.getStatus());
			return null;
		}
		
		String result = response.getEntity(String.class);
		Boolean logged = gson.fromJson(result, Boolean.class);
		return logged ? afterClient.getEntity(User.class, user) : null;
		
	}
	
	public User signup(User user, String pwd) {
		String requestPath = prop.getProperty("SIGNUP");
		WebResource webResource = client
				   .resource(path+requestPath);
		Map<String,Object> logParams = new HashMap<String, Object>();
		logParams.put("USER", user);
		logParams.put("PASSWORD",pwd);
		Gson gson = new Gson();
		ClientResponse response = webResource.type(MediaType.APPLICATION_JSON).post(ClientResponse.class,  gson.toJson(logParams));
		
		if (response.getStatus() != 201) {
			Properteer.getInstance().getLogger(this.getClass()).debug("Failed : HTTP error code : " + response.getStatus());
			return null;
		}
		
		String result = response.getEntity(String.class);
		User signed = gson.fromJson(result, User.class);
		return signed;
		
	}
}
